
let 
    isMount = true,  // 该fiber是否是初次创建
    workInProcessHook = null; // 该fiber当前的hooks链

// 模拟react的每次更新
function schedule() {

    // 更新前将workInProcessHook重置为fiber保存的第一个Hook
    workInProcessHook = fiber.memoizedState;

    // 触发组件render
    fiber.stateNode();

    // 组件首次render为mount，以后再触发的更新为update
    isMount = false;
}

// setState的实际调用函数
function dispatchAction(queue, action) {

    // 创建update
    const update = {
        action,
        next: null
    }

    // 环形单向链表操作
    if (queue.pending === null) {
        update.next = update;
    } else {
        update.next = queue.pending.next;
        queue.pending.next = update;
    }

    // 模拟react开始调度更新
    schedule();

}


function useState(initialState) {

    let hook;

    if (isMount) {
        // mount 时需要创建hook
        hook = {
            queue: {
                pending: null,
            },
            memoizedState: initialState,
            next: null,
        }
        // 将hook插入fiber.memoizedState链表末尾
        if (!fiber.memoizedState) {
            fiber.memoizedState = hook;
        } else {
            workInProgressHook.next = hook;
        }
        // 移动workInProgressHook指针
        workInProgressHook = hook;

    } else {
        // update 时从workInProcessHook中取出该useState对应的hook
        hook = workInProcessHook;
        // 移动workInProgressHook指针
        workInProcessHook = workInProcessHook.next;
    }
    let baseState = hook.memoizedState;
    if (hook.queue.pending) {
        // 根据queue.pending中的update更新state

        // 获取update环状单向链表中第一个update
        let firstUpdate = hook.queue.pending.next;
        do {
            // 执行update action
            const action = firstUpdate.action;
            baseState = action(baseState);
            firstUpdate = firstUpdate.next;
        
            // 最后一个update执行完后跳出循环
          } while (firstUpdate !== hook.queue.pending.next);

          // 清空queue.pending
          hook.queue.pending = null;
    }
    hook.memoizedState = baseState;

    return [baseState, dispatchAction.bind(null, hook.queue)];
}

// fiber数据结构
// const fiber = {
//     memoizedState: null, // hooks 链表

//     stateNode: App, // 指向app函数，用于更新
// }

// hook数据结构

// const hook = {
//     queue: {
//         pending: null,
//     },
//     memoizedState: initialState,
//     next: null,
// }